package com.tensquare.manager.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IDEA
 * author:zhiXiang-Chen
 * Date:2019/3/8
 * Time:22:41
 */
@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        try {
            RequestContext requestContext = RequestContext.getCurrentContext();
            HttpServletRequest request = requestContext.getRequest();

            //0 判断是否是跨域(如果做跨域请求时候，浏览器会自动发起一个 OPTIONS 方法到服务器。)
            if (request.getMethod().equals("OPTIONS")){
                return null;
            }

            //1.判断是否是登录
            if (request.getRequestURI().contains("/admin/login")) {
                System.out.println("登录...");
                return null;
            }

            //2.判断是否是管理员角色
            String authHeader = (String) request.getHeader("Authorization");//获取头信息
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                Claims claims = jwtUtil.parseJWT(token);
                if (claims != null) {
                    if ("admin".equals(claims.get("roles"))) {
                        requestContext.addZuulRequestHeader("Authorization", authHeader);
                        System.out.println("通过了验证...");
                        return null;
                    }
                }
            }
            //3.其它终止执行
            requestContext.setSendZuulResponse(false);//终止运行

            Result result = new Result(false, StatusCode.ACCESSERROR, "权限不足");

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(result);
            requestContext.setResponseStatusCode(401);//http状态码

            //设置乱码
            HttpServletResponse response = requestContext.getResponse();
            response.setContentType("application/json;charset=utf-8");
            requestContext.setResponseBody(jsonStr);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
